package com.test.springboot3.springboot3testdemo1.customizer;

import lombok.extern.slf4j.Slf4j;
import org.apache.hc.client5.http.classic.HttpClient;
import org.apache.hc.client5.http.config.RequestConfig;
import org.apache.hc.client5.http.impl.classic.HttpClientBuilder;
import org.apache.hc.client5.http.impl.routing.DefaultProxyRoutePlanner;
import org.apache.hc.client5.http.routing.HttpRoutePlanner;
import org.apache.hc.core5.http.HttpException;
import org.apache.hc.core5.http.HttpHost;
import org.apache.hc.core5.http.protocol.HttpContext;
import org.springframework.boot.web.client.RestTemplateCustomizer;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/8/2-下午7:06
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
@Component
public class CustomRestTemplateCustomizer implements RestTemplateCustomizer {

  /**
   * @param restTemplate the template to customize
   */
  @Override
  public void customize(RestTemplate restTemplate) {
    HttpRoutePlanner httpRoutePlanner =
        new CustomHttpRoutePlanner(new HttpHost("proxy.javastack.cn"));
    RequestConfig requestConfig = RequestConfig.custom().build();
    HttpClient httpClient =
        HttpClientBuilder.create()
            .setDefaultRequestConfig(requestConfig)
            .setRoutePlanner(httpRoutePlanner)
            .build();
    restTemplate.setRequestFactory(
        new org.springframework.http.client.HttpComponentsClientHttpRequestFactory(httpClient));
  }

  static class CustomHttpRoutePlanner extends DefaultProxyRoutePlanner {

    public CustomHttpRoutePlanner(HttpHost proxy) {
      super(proxy);
    }

    /**
     * @param target
     * @param context
     * @return
     * @throws HttpException
     */
    @Override
    protected HttpHost determineProxy(HttpHost target, HttpContext context) throws HttpException {
      log.info("host name is {}", target.getHostName());
      if ("localhost".equals(target.getHostName())) {
        return null;
      }
      return super.determineProxy(target, context);
    }
  }
}
